<template>
  <div class="main">
    <van-nav-bar
      title="收货地址"
      left-arrow
      @click-left="$router.back()"
    />
    <div class="address-list">
      <van-radio-group v-model="defaultId" @change="changeDefaultId(defaultId)">
        <AddressItem v-for="(item) in list" :key="item.address_id" :item="item" :defaultId="defaultId" @change="handleDelete">
        </AddressItem>
      </van-radio-group>
    </div>
    <div class="footer">
      <van-button type="primary" round size="large" color="linear-gradient(90deg,red,#fd5f36)"
      @click="$router.push({
      path: '/addaddress',
      query: {
        mode: 'add'
      }
      })">
        添加地址
      </van-button>
    </div>
  </div>

</template>

<script>
import AddressItem from '@/components/AddressItem.vue'
import { getAddressList, getDefaultAddress, removeAddress, setDefaultAddress } from '@/api/address'
import { getDefaultId, setDefaultId } from '@/utils/storage'
export default {
  name: 'AddressList',
  data () {
    return {
      list: [],
      defaultId: getDefaultId()
    }
  },
  components: {
    AddressItem
  },
  created () {
    this.updateList()
    this.getDefaultAddress()
  },
  methods: {
    async updateList () {
      const res = await getAddressList()
      this.list = res.data.list
    },
    handleDelete (id) {
      this.$dialog.confirm({
        title: '温馨提示',
        message: '确认删除吗'
      })
        .then(async () => {
          const res = await removeAddress(id)
          // on confirm
          if (res.status === 200) {
            this.$toast.success(res.message)
            this.updateList()
          }
        })
        .catch(() => {
          // on cancel
        })
    },
    async getDefaultAddress () {
      const res = await getDefaultAddress()
      // console.log(res)
      if (res.status !== 200 && this.defaultId === 0) {
        this.defaultId = this.list[0].address_id
        console.log(this.defaultId)
        console.log(this.list)
      }
      if (res.status === 200) {
        this.defaultId = res.data.defaultId
        setDefaultId(this.defaultId)
      }
    },
    async changeDefaultId (id) {
      const res = await setDefaultAddress(id)
      // console.log(res)
      if (res.status === 200) {
        setDefaultId(id)
        console.log(res)
      }
    }
  }
}
</script>

<style scoped lang="less">
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
html, body {
  margin: 0;
  height: 100vh;
  position: relative;
}
.main {
  width: 100%;
  min-height: 100vh;
  background-color: rgba(239, 239, 239, 0.35);
  position: relative;
  .footer {
    position: fixed;
    width: 100%;
    height: 90px;
    bottom: 0;
    background-color: #ffffff;
    padding: 20px 10px 0;
  }
}

</style>
